package org.dromara.bean.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Administrator
 */
public class BaiduMapUtil {
    /**
     * 百度地图请求秘钥
     */
//    private static final String KEY = "LdCF6K0nBNNRtkHimO4k3ggPlCzqdNtI";
    private static final String KEY = "sLeMKfNagQFVzG3GaIgWyOzBGG09rkuP";
    /**
     * 返回值类型
     */
    private static final String OUTPUT = "json";
    /**
     * 根据经纬度获取地名
     * http://api.map.baidu.com/reverse_geocoding/v3/?ak=sLeMKfNagQFVzG3GaIgWyOzBGG09rkuP&output=json&coordtype=wgs84ll&location=$lat,$lng
     * http://api.map.baidu.com/reverse_geocoding/v3/?ak=自己百度地图的ak&output=json&coordtype=wgs84ll&location=维度,经度
     */
    private static final String GET_ADDRESS_URL = "http://api.map.baidu.com/reverse_geocoding/v3/";

    private BaiduMapUtil() {
        throw new AssertionError("不能产生实例");
    }

    public static void main(String[] args) {
        JSONObject obj = getCity("38.307232", "106.125456").getJSONObject("result");
        System.out.println("地区编码：" + obj.getJSONObject("addressComponent").getString("adcode"));
        System.out.println("地址：" + obj.getString("formatted_address"));
        System.out.println(getLngAndLat("浙江省杭州市萧山区民和路"));
    }

    public static String getRegionCode(String lat, String lng) {
        JSONObject result = getCity(lat, lng);
        if (result == null) {
            return "";
        }
        String code = result.getJSONObject("addressComponent").getString("adcode");
        return code;
    }

    /**
     * 百度地图通过经纬度来获取地址,传入参数纬度lat、经度lng
     *
     * @param lat
     * @param lng
     * @return
     */
    public static JSONObject getCity(String lat, String lng) {

        Map<String, String> paramsMap = new LinkedHashMap<String, String>();
        paramsMap.put("location", lat + "," + lng);
        paramsMap.put("output", OUTPUT);
        paramsMap.put("coordtype", "wgs84ll");
        paramsMap.put("ak", KEY);
        String resultString;
        JSONObject obj;
        //发送请求
        resultString = HttpUtil.doGet(GET_ADDRESS_URL, paramsMap);
        //转换为josn字符串
        obj = JSON.parseObject(resultString);

        return (JSONObject) obj.get("result");
    }

    /**
     * 百度地图通过地址来获取经纬度，传入参数address
     *
     * @param address
     * @return
     */
    public static JSONObject getLngAndLat(String address) {
        Map<String, String> paramsMap = new LinkedHashMap<String, String>();
        paramsMap.put("address", address);
        paramsMap.put("output", "json");
        paramsMap.put("ak", KEY);
        String res;
        JSONObject obj = null;
        //发送请求
        res = HttpUtil.doGet(GET_ADDRESS_URL, paramsMap);
        //转换为josn字符串
        obj = JSON.parseObject(res);

        return obj;
    }

    //sn就是要计算的，sk不需要在url里出现，但是在计算sn的时候需要sk（假设sk=yoursk）
    private static String getSN(Map<String, String> paramsMap) {

        String sn = null;
        try {
            // 调用下面的toQueryString方法，对LinkedHashMap内所有value作utf8编码，拼接返回结果address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourak
            String paramsStr = toQueryString(paramsMap);
            // 对paramsStr前面拼接上/geocoder/v2/?，后面直接拼接yoursk得到/geocoder/v2/?address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourakSK
            String wholeStr = new String("/geocoder/v2/?" + paramsStr + KEY);
            // 对上面wholeStr再作utf8编码
            String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
            // 调用下面的MD5方法得到最后的sn签名7de5a22212ffaa9e326444c75a58f9a0
            sn = MD5(tempStr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sn;
    }

    // 对Map内所有value作utf8编码，拼接返回结果
    private static String toQueryString(Map<?, ?> data) {
        StringBuffer queryString = null;
        try {
            queryString = new StringBuffer();
            for (Map.Entry<?, ?> pair : data.entrySet()) {
                queryString.append(pair.getKey() + "=");
                queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
            }
            if (queryString.length() > 0) {
                queryString.deleteCharAt(queryString.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return queryString.toString();
    }

    // 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
    private static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getAdd(String log, String lat) {
        //lat 小 log 大
        //参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }
        System.out.println(res);
        return res;
    }

//    public static void main(String[] args) {
//        // lat 39.97646
//        //log 116.3039
//        String add = getAdd("116.3039", "39.97646");
//        JSONObject jsonObject = JSONObject.parseObject(add);
//        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("addrList"));
//        JSONObject j_2 = (JSONObject)jsonArray.get(0);
//        String allAdd = j_2.getString("admName");
//        String arr[] = allAdd.split(",");
//        System.out.println("省："+arr[0]+"\n市："+arr[1]+"\n区："+arr[2]);
//    }

}

